/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.oss.store.impl

import com.gitee.minimalismstyle.fresh.common.core.extra.write
import com.gitee.minimalismstyle.fresh.oss.api.model.OssFile
import com.gitee.minimalismstyle.fresh.oss.store.Store
import org.springframework.data.mongodb.core.query.Criteria
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.gridfs.GridFsOperations
import org.springframework.data.mongodb.gridfs.GridFsResource
import org.springframework.stereotype.Service
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.*

/**
 * mongodb存储文件，支持分布式
 * @author maoxiaodong
 */
@Service
class GridFsStore(private val operations: GridFsOperations) : Store {

    override fun write(ossFile: OssFile, inputStream: InputStream): String {
        val path = UUID.randomUUID().toString()
        operations.store(inputStream, path)
        return path
    }

    override fun read(ossFile: OssFile, os: OutputStream) {
        val resource: GridFsResource = operations.getResource(ossFile.path!!)
        resource.inputStream.use {
            it.write(os, ossFile.size!!.toInt())
        }
    }

    override fun read(ossFile: OssFile): InputStream {
        val resource: GridFsResource = operations.getResource(ossFile.path!!)
        return resource.inputStream
    }

    override fun delete(path: String) {
        val query = Query(Criteria.where("filename").`is`(path))
        operations.delete(query)
    }
}